package priv.pfz.basedao.jdbctemplate;

import com.google.common.collect.ImmutableSet;
import priv.pfz.basedao.apt.AptUtils;
import priv.pfz.basedao.info.AbstractDaoInfoParser;
import priv.pfz.basedao.info.DaoInfo;
import priv.pfz.basedao.jdbctemplate.dao.impl.DefaultBaseDaoImpl;
import priv.pfz.basedao.jdbctemplate.dao.impl.DefaultShardingBaseDaoImpl;
import priv.pfz.basedao.jdbctemplate.dao.impl.SimpleBaseDaoImpl;
import priv.pfz.basedao.jdbctemplate.dao.impl.SimpleShardingBaseDaoImpl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.Set;

/**
 * @author yyjxp
 * 2024/8/3 23:58
 */
public class DaoInfoParser extends AbstractDaoInfoParser {
    private static final DaoInfoParser INSTANCE = new DaoInfoParser();

    private static final Set<Type> BASE_DAO_CLASSES = ImmutableSet.of(
            SimpleBaseDaoImpl.class,
            SimpleShardingBaseDaoImpl.class,
            DefaultBaseDaoImpl.class,
            DefaultShardingBaseDaoImpl.class
    );

    public static DaoInfo getDaoInfo(Class<?> daoClass) {
        return INSTANCE.parseDaoInfo(daoClass);
    }

    @Override
    protected String getDefaultTableName(Class<?> mapperClass) {
        return AptUtils.classToTable(mapperClass.getSimpleName().replace("DaoImpl", ""));
    }

    @Override
    protected Class<?> getEntityClass(Class<?> mapperClass) {
        Type genericSuperclass = mapperClass.getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType gi = (ParameterizedType) genericSuperclass;
            if (BASE_DAO_CLASSES.contains(gi.getRawType())) {
                return (Class<?>) gi.getActualTypeArguments()[0];
            }
        }
        throw new RuntimeException(MessageFormat.format("解析Dao类{0}异常", mapperClass.getSimpleName()));
    }
}
